package log

import (
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"higame/config"
)

type ShareLogSchema struct {
	ID         primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
	UUID       string             `json:"uuid" bson:"uuid"`
	AddTime    int64              `json:"add_time" bson:"add_time"`
	Master     string             `json:"master" bson:"master"`
	ShareCode  string             `json:"share_code" bson:"share_code"`
	Apprentice string             `json:"apprentice" bson:"apprentice"`
	IP         string             `json:"ip" bson:"ip"`
	Remark     string             `json:"remark" bson:"remark"`
}

var colLogShare = config.Db.Collection.LogShare

func NewShareLog() *ShareLogSchema {
	return &ShareLogSchema{}
}

func ParseShareLog(data bson.M) (*ShareLogSchema, error) {
	u := NewShareLog()
	if err := db.ToStruct(data, u); err != nil {
		return nil, err
	}
	return u, nil
}

func AddOneShareLog(log *ShareLogSchema) error {
	logI := db.InsertOne(colLogShare, log)
	if !logI {
		return errors.New("添加日志失败，可能是数据连接有问题")
	}
	return nil
}

func FindManyShareLog(pageNum int64, filter interface{}) []ShareLogSchema {
	if pageNum > 0 {
		pageNum = pageNum - 1
	}
	opts := new(options.FindOptions)
	list := db.FindMany(colLogShare, filter,
		opts.SetSkip(pageNum*20),
		opts.SetLimit(20),
		opts.SetSort(bson.M{
			"add_time": -1,
		}))
	var logs = make([]ShareLogSchema, 0)
	for _, v := range list {
		if log, err := ParseShareLog(v); err == nil {
			logs = append(logs, *log)
		}
	}
	return logs
}

func CountShareLog(filter interface{}) (int64, error) {
	return db.Count(colLogShare, filter), nil
}
